<template>
  <div class="game-view">
    <Tabs @on-click="selectGame" v-if="gameList.length > 0">
      <TabPane :label="item.name" v-for="item in gameList" :key="item.id">
        <Row>
          <Col span="24">
            <Form ref="formInline" inline>
              <FormItem>
                <Button type="primary" @click="onClickSaveAccountBtn">添加游戏账号</Button>
              </FormItem>
            </Form>

            <Row>
              <Col span="24">
                <Table border :loading="loading" :columns="tbCol" :data="list" size="small">
                  <template slot-scope="{ row, index }" slot="account">
                    {{ row.account }}(等级{{ row.level }})
                  </template>
                  <template slot-scope="{ row, index }" slot="price">
                    {{ row.price | moneyFormat }}元
                  </template>
                  <template slot-scope="{ row, index }" slot="s1">
                    {{ row.s1 | moneyFormat }}
                  </template>
                  <template slot-scope="{ row, index }" slot="s2">
                    {{ row.s2 | moneyFormat }}
                  </template>
                  <template slot-scope="{ row, index }" slot="img">
                    <img class="icon" :src="row.img"/>
                  </template>
                  <template slot-scope="{ row, index }" slot="recommend">
                    <Tag v-if="row.topLevel" color="blue">顶级账号</Tag>
                    <Tag v-if="row.up" color="green">置顶强推</Tag>
                  </template>
                  <template slot-scope="{ row, index }" slot="tag">
                    <Tag v-for="item in row.tagInfoList" :key="item.id">{{ item.name }}</Tag>
                  </template>
                  <template slot-scope="{ row, index }" slot="action">
                    <Button type="primary" size="small" style="margin-right: 5px" @click="onClickSaleAccountBtn(row)">
                      出售
                    </Button>
                    <Button type="primary" size="small" style="margin-right: 5px" @click="onClickSaveAccountBtn(row)">
                      编辑
                    </Button>
                    <Button type="error" size="small" @click="onClickDeleteAdBtn(row)">删除</Button>
                  </template>
                </Table>
              </Col>
            </Row>

            <div class="clear-10"></div>
            <Row>
              <Col span="24">
                <Page :total="total" :page-size="pageSize" show-total @on-change="pageChange"/>
              </Col>
            </Row>
          </Col>
        </Row>
      </TabPane>
    </Tabs>

    <div v-else>
      空空如也~，请先添加游戏
    </div>
    <Modal
      v-model="saveModel.show"
      :loading="saveModel.loading"
      :title="saveModel.title"
      fullscreen
      @on-cancel="cancelModal"
      @on-ok="saveAccount('accountForm')">
      <Form ref="accountForm" :model="accountForm" :rules="ruleValidate" :label-width="80">
        <FormItem label="账号" prop="account">
          <Row :gutter="20">
            <Col span="4">
              <Input clearable v-model="accountForm.account" placeholder="请输入账号"></Input>
            </Col>
            <Col span="4">
              <Input clearable v-model="accountForm.level" type="number" placeholder="请输入账号等级"></Input>
            </Col>
            <Col span="6">
              <CheckboxGroup v-model="accountForm.attr">
                <Checkbox label="顶级账号"></Checkbox>
                <Checkbox label="置顶强推"></Checkbox>
              </CheckboxGroup>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="属性">
          <Row :gutter="20">
            <Col span="4">
              <Input clearable v-model="accountForm.hot" type="number" placeholder="请输入热度"></Input>
            </Col>
            <Col span="4">
              <Input clearable v-model="accountForm.s1" type="number" placeholder="请输入魅力"></Input>
            </Col>
            <Col span="4">
              <Input clearable v-model="accountForm.s2" type="number" placeholder="请输入功力"></Input>
            </Col>
            <Col span="4">
              <Input clearable v-model="accountForm.price" type="number" placeholder="请输入价格"></Input>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="标签">
          <Row :gutter="20">
            <Col span="16">
              <Select v-model="accountForm.gameTagInfoList" multiple>
                <OptionGroup :label="item.name" v-for="item in tagList" :key="item.id">
                  <Option v-for="tag in item.gameTagInfoList" :value="tag.id" :key="tag.id">{{ tag.name }}</Option>
                </OptionGroup>
              </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="上架时间">
          <Row :gutter="20">
            <Col span="4">
              <DatePicker placeholder="请选择时间" v-model="accountForm.launchTime"></DatePicker>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="标题" prop="title">
          <Row :gutter="20">
            <Col span="16">
              <Input clearable v-model="accountForm.title" placeholder="请输入标题"></Input>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="封面图">
          <Row :gutter="20">
            <Col span="16">
              <div class="img-upload">
                <div class="demo-upload-list" v-if="img.length > 0">
                  <template>
                    <img :src="img">
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline" @click.native="handleView(img)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="handleRemove(index)"></Icon>
                    </div>
                  </template>
                </div>
              </div>
              <Upload :action="Core.Const.NET.UPLOAD_FILE_URL"
                      :show-upload-list="false"
                      :on-success="handleUploadSuccess">
                <Button icon="ios-cloud-upload-outline">上传</Button>
              </Upload>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="详情">
          <Row :gutter="20">
            <Col span="23">
              <editor ref="editor" :value="content" @on-change="handleChange"/>
            </Col>
          </Row>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      v-model="delModel.show"
      title="提示"
      class-name="del-modal"
      @on-ok="delAccount">
      <p>确定要删除该账号么?</p>
    </Modal>
    <Modal
      v-model="soldModel.show"
      title="提示"
      class-name="del-modal"
      @on-ok="soldAccount">
      <p>确定要出售该账号么?</p>
    </Modal>
  </div>
</template>

<script>
import Editor from '_c/editor'
import Core from 'core/core'

export default {
  components: {
    Editor
  },
  data() {
    return {
      Core: Core,
      loading: true,
      tbCol: [
        {title: 'ID', key: 'id', width: '80px'},
        {title: '账号', slot: 'account', width: '150px'},
        {title: '标题', key: 'title', width: '300px'},
        {title: '价格', slot: 'price', width: '100px'},
        {title: '图片', slot: 'img', width: '180px'},
        {title: '推荐', slot: 'recommend', width: '150px'},
        {title: '标签', slot: 'tag', width: '200px'},
        {title: '热度', key: 'hot', width: '80px'},
        {title: '魅力', slot: 's1', width: '80px'},
        {title: '功力', slot: 's2', width: '80px'},
        {title: '操作', slot: 'action', width: 180, align: 'center', fixed: 'right'}
      ],
      list: [],
      currentPage: 1,
      total: 0,
      pageSize: 10,

      accountForm: {
        id: 0,
        title: '',
        account: '',
        level: '',
        attr: [],
        hot: '',
        s1: '',
        s2: '',
        price: '',
        gameId: '',
        launchTime: '',
        gameTagInfoList: []
      },
      img: [],
      content: '',
      ruleValidate: {
        account: [
          {required: true, message: '账号不能为空', trigger: 'blur'}
        ],
        title: [
          {required: true, message: '标题不能为空', trigger: 'blur'}
        ]
      },
      saveModel: {
        show: false,
        title: '',
        loading: true
      },
      delModel: {
        show: false,
        id: 0
      },
      soldModel: {
        show: false,
        id: 0
      },
      gameList: [],
      tagList: []
    }
  },
  mounted() {
    this.getGameList()
  },
  methods: {
    getGameList() {
      Core.Api.Game.list({})
        .then(res => {
          this.gameList = res.list
          if (this.gameList.length > 0) {
            this.accountForm.gameId = this.gameList[0].id;
            this.getGameAccountList(this.accountForm.gameId)
            this.getGameListWithTag(this.accountForm.gameId)
          }
        })
    },
    getGameListWithTag(gameId) {
      Core.Api.GameTag.listWithTag({gameId: gameId})
        .then(res => {
          this.tagList = res.list
        });
    },
    getGameAccountList(gameId) {
      this.loading = true
      Core.Api.GameAccount.list({gameId: gameId, status: 1, page: this.currentPage})
        .then(res => {
          this.loading = false
          this.list = res.list
          this.total = res.count
        })
    },
    pageChange(page) {
      this.currentPage = page
      this.getGameAccountList(this.accountForm.gameId)
    },
    selectGame(idx) {
      this.accountForm.gameId = this.gameList[idx].id;
      this.getGameAccountList(this.accountForm.gameId)
      this.getGameListWithTag(this.accountForm.gameId)
    },
    handleChange(html, text) {
      this.content = html;
    },
    onClickSaveAccountBtn(item) {
      this.saveModel.title = item.id ? '编辑游戏账号' : '添加游戏账号'
      this.accountForm.id = item.id ? item.id : 0;
      this.accountForm.title = item.id ? item.title : ''
      this.accountForm.account = item.id ? item.account : ''
      this.accountForm.level = item.id ? item.level : ''
      this.accountForm.attr = []
      if (item.id) {
        if (item.topLevel) {
          this.accountForm.attr.push('顶级账号')
        }
        if (item.up) {
          this.accountForm.attr.push('置顶强推')
        }
      }
      this.accountForm.launchTime = item.id ? new Date(item.launch_time) : ''
      this.accountForm.hot = item.id ? item.hot : ''
      this.accountForm.s1 = item.id ? (item.s1 / 100.0).toFixed(2) : ''
      this.accountForm.s2 = item.id ? (item.s2 / 100.0).toFixed(2) : ''
      this.accountForm.price = item.id ? (item.price / 100.0).toFixed(2) : ''
      this.accountForm.gameTagInfoList = item.id ? item.gameTagInfoList.split(",").map(Number) : []
      this.content = item.id ? item.content : ''
      this.$refs.editor.setHtml(this.content)
      this.img = item.id ? item.img : ''
      this.saveModel.show = true
    },
    onClickDeleteAdBtn(item) {
      this.delModel.id = item.id
      this.delModel.show = true
    },
    cancelModal() {
      this.$refs.accountForm.resetFields()
    },
    handleUploadSuccess(res) {
      this.img = [res.data]
    },
    handleView(name) {
      this.previewModel.img = name;
      this.previewModel.visible = true;
    },
    handleRemove(index) {
      this.img = []
    },
    saveAccount(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let id = this.accountForm.id

          function sortNumber(a, b) {
            return a - b
          }

          let data = {
            id: this.accountForm.id,
            title: this.accountForm.title,
            account: this.accountForm.account,
            level: this.accountForm.level,
            img: this.img,
            hot: this.accountForm.hot,
            s1: Number(this.accountForm.s1).toFixed(2) * 100,
            s2: Number(this.accountForm.s2).toFixed(2) * 100,
            price: Number(this.accountForm.price).toFixed(2) * 100,
            content: this.content,
            gameId: this.accountForm.gameId,
            topLevel: 0,
            up: 0,
            gameTagInfoList: this.accountForm.gameTagInfoList.sort((a, b) => a - b).join(","),
            launchTime: this.accountForm.launchTime
          }

          this.accountForm.attr.forEach(v => {
            if (v === '顶级账号') {
              data.topLevel = 1;
            } else if (v === '置顶强推') {
              data.up = 1;
            }
          })

          Core.Api.GameAccount.save(data).then(() => {
            this.$Message.success(id ? '修改成功！' : '添加成功！')
            this.getGameAccountList(id)
            this.saveModel.show = false
            this.$refs.accountForm.resetFields()
            this.content = ''
            this.img = []
          }).catch(err => {
            this.saveModel.loading = false
            setTimeout(() => {
              this.saveModel.loading = true
            })
          })
        } else {
          this.saveModel.loading = false
          setTimeout(() => {
            this.saveModel.loading = true
          })
        }
      })
    },
    delAccount() {
      let data = {
        id: this.delModel.id
      }
      Core.Api.GameAccount.delete(data)
        .then(() => {
          this.$Message.success('删除成功！')
          this.currentPage = 1
          this.getGameAccountList(this.accountForm.gameId)
        }).catch(err => {
        this.$Message.error(err.msg)
      })
    },
    onClickSaleAccountBtn(item) {
      this.soldModel.id = item.id
      this.soldModel.show = true
    },
    soldAccount() {
      let data = {
        id: this.soldModel.id
      }
      Core.Api.GameAccount.sold(data)
        .then(() => {
          this.$Message.success('售出成功！')
          this.currentPage = 1
          this.getGameAccountList(this.accountForm.gameId)
        }).catch(err => {
        this.$Message.error(err.msg)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.game-view {
  background: #fff;
  border-radius: 4px;
  font-size: 14px;
  position: relative;
  padding: 16px;

  .icon {
    width: 140px;
    padding: 10px 0;
  }
}

.demo-upload-list {
  display: inline-block;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
